﻿define(['app'], function (app) {
    app.lazy.controller("EditChapterController", [
        "$scope",
        "$http",
        "$routeParams",
        "$resource",
        function ($scope, $http, $routeParams, $resource) {
            $scope.tinymceOptions = {
                handle_event_callback: function (e) {
                    // put logic here for keypress
                }
            };

            $scope.paging = {
                PageSize: 10
            };

            var bookId = $routeParams.bookId;

            if (!bookId) {
                // TODO: book unspecified
            }

            $scope.pageChanged = function (page) {
                $scope.paging.PageIndex = page - 1;
                var url = "/dashboard/services/chapter/getbybook?bookId=" + bookId;
                url += "&PageSize=" + $scope.paging.PageSize;
                url += "&PageIndex=" + $scope.paging.PageIndex;

                $http.get(url).success(function (data) {
                    $scope.chapters = data.Chapters;
                    $scope.paging = data.Paging;

                    $scope.showPaging = data.Paging && data.Paging.TotalPages && parseInt(data.Paging.TotalPages) > 1;

                    if ($scope.chapters && $scope.chapters.length > 0) {
                        $scope.loadChapter($scope.chapters[0].Id);
                    } else {
                        $scope.chapters = [];
                    }

                    $scope.chapters.swapItems = function (a, b) {
                        var tmp = this[a].SortOrder;
                        this[a].SortOrder = this[b].SortOrder;
                        this[b].SortOrder = tmp;
                        this[a] = this.splice(b, 1, this[a])[0];
                        return this;
                    }
                });
            };

            $scope.loadChapter = function (id) {
                var url = "/dashboard/services/chapter/" + id;
                $http.get(url).success(function (data) {
                    $scope.currentChapter = data;
                });
            };

            $scope.moveUp = function (index) {
                var index = parseInt(index);
                if (index < 1 || index > $scope.chapters.length - 1) return;

                $scope.chapters.swapItems(index, index - 1);
            };
            $scope.moveDown = function (index) {
                var index = parseInt(index);
                if (index < 0 || index > $scope.chapters.length - 2) return;

                $scope.chapters.swapItems(index, index + 1);
            };

            $scope.pageChanged(1);
        }
    ]);

    app.lazy.filter("chapterTitle", function () {
        return function (title, index) {
            if (title) return title;
            
            var $index = parseInt(index);
            return "Chapter " + ($index + 1);
        };
    });
});